package com.xiaowu.house.house.controller;

import com.xiaowu.house.domain.R;
import com.xiaowu.house.domain.dto.BasePageDTO;
import com.xiaowu.house.domain.vo.BasePageVO;
import com.xiaowu.house.house.domain.dto.*;
import com.xiaowu.house.house.domain.vo.HouseDetailVO;
import com.xiaowu.house.house.domain.vo.HouseVO;
import com.xiaowu.house.house.feign.HouseFeignClient;
import com.xiaowu.house.house.service.IHouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RestController
@RequestMapping("/house")
public class HouseController implements HouseFeignClient {

    @Autowired
    IHouseService houseService;

    /**
     * 新增或编辑房源
     * @param houseAddOrEditReqDTO 请求DTO
     * @return 房子ID
     */
    @PostMapping("/add_edit")
    public R<Long> addOrEdit(@Validated @RequestBody HouseAddOrEditReqDTO
                                     houseAddOrEditReqDTO) {
        return R.ok(houseService.addOrEdit(houseAddOrEditReqDTO));
    }

    /**
     * 查询房源详情（带缓存）
     */
    @GetMapping("/detail")
    @Override
    public R<HouseDetailVO> detail(Long houseId) {
        HouseDTO houseDTO = houseService.detail(houseId);
        if (null == houseDTO) {
            log.warn("要查询的房源不存在，houseId:{}", houseId);
            return R.fail("房源详情不存在！");
        }
        return R.ok(houseDTO.convertToVO());
    }

    /**
     * 查询房源摘要列表（支持翻页、支持筛选）
     */
    @PostMapping("/list")
    public R<BasePageVO<HouseVO>> list(@Validated @RequestBody HouseListReqDTO houseListReqDTO) {
        BasePageDTO<HouseDescDTO> houseDescList = houseService.list(houseListReqDTO);
        BasePageVO<HouseVO> result = new BasePageVO<>();
        BeanUtils.copyProperties(houseDescList, result);
        return R.ok(result);
    }

    /**
     * 更新房源状态
     * @param houseStatusEditReqDTO 房源状态更新请求DTO
     * @return 统一返回结果
     */
    @PostMapping("/status/edit")
    public R<?> editStatus(@Validated @RequestBody HouseStatusEditReqDTO houseStatusEditReqDTO) {
        houseService.editStatus(houseStatusEditReqDTO);
        return R.ok();
    }

    @GetMapping("/refresh")
    public R<Void> refreshHouseIds() {
        houseService.refreshHouseIds();
        return R.ok();
    }
}
